/* eslint-disable react-hooks/rules-of-hooks */
import React, {
  forwardRef,
  useState,
  useRef,
  useImperativeHandle,
  useEffect,
  useMemo,
} from 'react';
import styles from './style.less';
import { PageContainer } from '@ant-design/pro-layout';
import { EllipsisOutlined } from '@ant-design/icons';
import { ProColumns, ProTable, ProDescriptions, ProCard } from '@ant-design/pro-components';
import { Button, Space, Drawer, Tag, Tree, Input, Badge } from 'antd';
import { getListType, getDictListPage, getDetail } from '@/services/api/setting/dict';
import { reject } from 'lodash';
import { buildParams } from '@/utils/paramUtils';
import { tableSuppert } from '@/utils/response';
const { Search } = Input;

const stateValueEnum = {
  0: {
    text: '不封存',
    status: 'Processing',
  },
  1: {
    text: '封存',
    status: 'Success',
  },
};

const bizValueEnum = {
  1: { text: '其他' },
  2: { text: '新增' },
  3: { text: '修改' },
  4: { text: '删除' },
  5: { text: '授权' },
  6: { text: '导出' },
  7: { text: '导入' },
  8: { text: '强退' },
  9: { text: '生成代码' },
  10: { text: '清空数据' },
};

const operatorValueEnum = {
  0: { text: '其他' },
  1: { text: '电脑端' },
  2: { text: '移动端' },
};

export default function dict() {
  // 列
  const columns = [
    {
      title: '#',
      dataIndex: 'index',
      valueType: 'indexBorder',
      hideInSearch: true,
      width: 48,
    },
    {
      title: '编号',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '字典标签',
      dataIndex: 'dictLabel',
      key: 'dictLabel',
    },

    {
      title: '字典样式',
      dataIndex: 'style',
      key: 'style',
      render: (text, record, index, action) => (
        <Space>
          {record.style.indexOf('#') <= -1 ? (
            <Badge status={record.style} text={record.style} />
          ) : (
            <Badge color={record.style} text={record.style} />
          )}
        </Space>
      ),
    },
    {
      title: '字典键值',
      dataIndex: 'dictValue',
      key: 'dictValue',
    },
    {
      title: '系统默认',
      dataIndex: 'hasDefault',
      key: 'hasDefault',
      valueEnum: {
        Y: {
          text: '是',
        },
        N: {
          text: '否',
        },
      },
      render: (text, record, index, action) => (
        <Space>
          {record.hasDefault === 'Y' ? (
            <Tag color="blue">{text}</Tag>
          ) : (
            <Tag color="green">{text}</Tag>
          )}
        </Space>
      ),
    },
    {
      title: '封存',
      dataIndex: 'status',
      key: 'status',
      valueEnum: {
        0: {
          text: '不封存',
          status: 'Processing',
        },
        1: {
          text: '封存',
          status: 'Success',
        },
      },
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      key: 'createBy',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      hideInTable: true,
    },
    {
      title: '修改人',
      dataIndex: 'modifyBy',
      key: 'modifyBy',
      hideInTable: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      hideInTable: true,
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
      hideInTable: true,
    },
    {
      title: '操作',
      key: 'action',
      hideInSearch: true,
      render: (text, record, index, action) => [
        <Space key="action">
          <a key="view" onClick={() => showView(record.id)}>
            查看
          </a>
          <a key="delete" onClick={() => remove(record.id)}>
            编辑
          </a>
          <a key="delete1" onClick={() => remove(record.id)}>
            删除
          </a>
        </Space>,
      ],
    },
  ];

  // 删除操作
  const remove = (ids) => {};
  // 查看详情
  const showView = (id) => {
    setOpen(true);
    setId(id);
    setTimeout(() => {
      drawerRef.current.reloadDescriptions();
    });
  };
  //抽屉是否显示
  const [open, setOpen] = useState(false);
  // id值
  const [id, setId] = useState(0); //id
  // 子组件ref
  const drawerRef = useRef(null);
  // 树数据
  const [treeList, setTreeList] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  //选中节点
  const [checkNodeKey, setCheckNodeKey] = useState('');
  // 表格ref
  const dictTableRef = useRef();

  // 展开
  const onExpand = (newExpandedKeys) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  // 高亮对象
  const loop = (data) =>
    data.map((item) => {
      const strTitle = item.title;
      const index = strTitle.indexOf(searchValue);
      const beforeStr = strTitle.substring(0, index);
      const afterStr = strTitle.slice(index + searchValue.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span className={styles.siteTreeSearchValue}>{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span>{strTitle}</span>
        );

      if (item.children) {
        return {
          title,
          key: item.key,
          parentId: item.parentId,
          selectable: item.selectable,
          sort: item.sort,
          children: loop(item.children),
        };
      }

      return {
        title,
        key: item.key,
        parentId: item.parentId,
        selectable: item.selectable,
        sort: item.sort,
      };
    });

  // 发起网络请求
  const getTreeType = async () => {
    await getListType().then((res) => {
      setTreeList(res.data);
    });
  };

  // 请求树形type
  useEffect(() => {
    getTreeType();
  }, []);

  // 用于临时将转换非树数组
  const dataList = [];

  // 生成树
  const generateList = (data) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key, title, parentId, selectable, sort } = node;
      dataList.push({ key, title: title, parentId: parentId, selectable: selectable, sort: sort });
      if (node.children) {
        generateList(node.children);
      }
    }
  };

  // 调用生成
  generateList(treeList);

  // 获取父节点
  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  // 搜索
  const onChange = (e) => {
    let { value } = e.target;
    value = String(value).trim();
    if (value === '') {
      setExpandedKeys([]);
      setAutoExpandParent(false);
      setSearchValue('');
    }
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          console.log(item.key);
          return getParentKey(item.key, treeList);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(true);
    setSearchValue(value);
  };

  return (
    <PageContainer content="系统数据字典">
      <ProCard split="vertical">
        <ProCard colSpan="15%">
          <Search
            style={{
              marginBottom: 8,
            }}
            placeholder="Search"
            onChange={onChange}
          />
          <Tree
            height={500}
            defaultExpandAll
            onSelect={(selectedKeys) => {
              setCheckNodeKey(selectedKeys[0]);
              dictTableRef.current.reload();
            }}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            treeData={loop(treeList)}
          />
        </ProCard>
        <ProCard>
          <ProTable
            actionRef={dictTableRef}
            // 聚焦加载 false
            revalidateOnFocus={false}
            // 等分每列
            tableLayout="fixed"
            // 分页配置
            pagination={{ defaultPageSize: 10, showQuickJumper: true }}
            // 表头
            columns={columns}
            // 发请求
            request={async (param, sorter) => {
              // if (Object.keys(sorter).length === 0) {
              //   sorter.operatorTime = 'desc';
              // }
              // 设置选中节点，带条件查询
              param['dictTypeId'] = checkNodeKey;
              const data = await getDictListPage(buildParams(param, sorter)).then((res) => {
                return res.data;
              });
              return tableSuppert(data);
            }}
            // 选择
            rowSelection={{}}
            // 关键key
            rowKey="id"
            //开启搜索
            search={true}
            tableAlertOptionRender={({ selectedRowKeys }) => {
              return (
                <Space size={16}>
                  <a>批量删除</a>
                  <a>导出数据</a>
                </Space>
              );
            }}
          />
        </ProCard>
      </ProCard>

      <ShowDrawer ref={drawerRef} id={id} open={open} setOpen={setOpen.bind(this)} />
    </PageContainer>
  );
}

/**
 * 详情子组件
 */
const ShowDrawer = forwardRef((props, ref) => {
  const detilaRef = useRef();

  // 刷新Descriptions
  const reloadDescriptions = () => {
    detilaRef.current.reload();
  };
  // 绑定函数
  useImperativeHandle(ref, () => ({
    reloadDescriptions,
  }));

  // 关闭抽屉
  const closeDrawer = () => {
    props.setOpen(false);
  };
  // 查询详情
  const getDictDetail = async () => {
    return new Promise((resolve, reject) => {
      getDetail(props.id)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  return (
    <Drawer title="查看" width="45%" open={props.open} onClose={closeDrawer}>
      <ProDescriptions
        actionRef={detilaRef}
        title="字典详情"
        bordered={true}
        request={async () => {
          return await getDictDetail();
        }}
      >
        <ProDescriptions.Item dataIndex="id" label="字典编号" span={1.5} />
        <ProDescriptions.Item dataIndex="dictLabel" label="字典标签" span={1.5} />
        <ProDescriptions.Item dataIndex="dictValue" label="字典键值" span={1.5} />
        <ProDescriptions.Item
          dataIndex="style"
          label="字典样式"
          span={1.5}
          render={(text, record) => {
            return (
              <Space>
                {record.style.indexOf('#') <= -1 ? (
                  <Badge status={record.style} text={record.style} />
                ) : (
                  <Badge color={record.style} text={record.style} />
                )}
              </Space>
            );
          }}
        />
        <ProDescriptions.Item
          dataIndex="hasDefault"
          label="是否默认"
          span={1.5}
          render={(text, record) => {
            return (
              <Space>
                {record.hasDefault === 'Y' ? (
                  <Tag color="blue">{text}</Tag>
                ) : (
                  <Tag color="green">{text}</Tag>
                )}
              </Space>
            );
          }}
        />
        <ProDescriptions.Item
          dataIndex="status"
          label="封存"
          span={1.5}
          valueEnum={stateValueEnum}
        />
        <ProDescriptions.Item dataIndex="createBy" label="创建人" span={1.5} />
        <ProDescriptions.Item dataIndex="createTime" label="创建时间" span={1.5} />
        <ProDescriptions.Item dataIndex="modifyBy" label="修改人" span={1.5} />
        <ProDescriptions.Item dataIndex="modifyTime" label="修改时间" span={1.5} />
        <ProDescriptions.Item dataIndex="remark" label="备注" span={3} />
      </ProDescriptions>
    </Drawer>
  );
});
